package com.qdc.datacenters.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qdc.datacenters.config.redis.RedisService;
import com.qdc.datacenters.constant.CacheConstants;
import com.qdc.datacenters.domain.entity.BaseEntity;
import com.qdc.datacenters.domain.entity.MsgEncryptConfig;
import com.qdc.datacenters.domain.entity.SysCorp;
import com.qdc.datacenters.domain.query.corp.SysCorpAddQuery;
import com.qdc.datacenters.domain.query.corp.SysCorpQuery;
import com.qdc.datacenters.enums.DeleteStatusEnum;
import com.qdc.datacenters.mapper.SysCorpMapper;
import com.qdc.datacenters.service.IMsgEncryptConfigService;
import com.qdc.datacenters.service.ISysCorpService;
import com.qdc.datacenters.utils.StrUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 企业信息表(SysCorp)表服务实现类
 *
 * @author danmo
 * @since 2024-02-27 18:44:20
 */
@Service
public class SysCorpServiceImpl extends BaseServiceImpl<SysCorpMapper, SysCorp> implements ISysCorpService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private IMsgEncryptConfigService encryptConfigService;

    @Override
    public void save(SysCorpAddQuery query) {
        String key = StrUtils.format(CacheConstants.SYS_CORP_INFO_TOKEN, query.getCorpId());
        redisService.deleteObject(key);
        SysCorp sysCorp = new SysCorp();
        BeanUtils.copyProperties(query,sysCorp);
        if(Objects.isNull(query.getId())){
            save(sysCorp);
        }else {
            updateById(sysCorp);
        }
        redisService.deleteObject(key);
    }

    @Override
    public SysCorp get(SysCorpQuery query) {
        String key = StrUtils.format(CacheConstants.SYS_CORP_INFO_TOKEN, query.getCorpId());
        SysCorp corp = (SysCorp) redisService.getCacheObject(key);
        if(Objects.isNull(corp)){
            corp =  getOne(new LambdaQueryWrapper<SysCorp>().eq(BaseEntity::getDelFlag, DeleteStatusEnum.DELETE_NO.getIndex()));
            if(Objects.nonNull(corp)){
                redisService.setCacheObject(key,corp,1, TimeUnit.DAYS);
            }
        }
        return corp;
    }

    @Override
    public void saveEncrypt(SysCorpAddQuery query) {
        MsgEncryptConfig msgEncryptConfig = new MsgEncryptConfig();
        msgEncryptConfig.setPublicKey(query.getEncryptPublicKey());
        msgEncryptConfig.setPrivateKey(query.getEncryptRandomKey());
        msgEncryptConfig.setVersion(query.getEncryptVersion());
        encryptConfigService.save(msgEncryptConfig);
    }


}

